package com.example.Web_chat.controller;

import com.example.Web_chat.component.ChatWebSocketAPI;
import com.example.Web_chat.mapper.FriendMapper;
import com.example.Web_chat.mapper.FriendRequestMapper;
import com.example.Web_chat.model.FriendRequest;
import com.example.Web_chat.model.User;
import com.example.Web_chat.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class UserController {
    @Resource
    UserMapper userMapper;

    @Autowired
    private FriendMapper friendMapper;

    @Autowired
    private FriendRequestMapper friendRequestMapper;



    @PostMapping("/login")
    @ResponseBody
    public Object login(String username, String password, HttpServletRequest req) {
        // 1. 先去数据库中查查, 看 username 能否找到对应的 user 对象
        //    如果能找到则看一下密码是否匹配
        User user = userMapper.selectByName(username);
        if (user == null || !user.getPassword().equals(password)) {
            // 这俩条件具备一个, 就是登录失败!! 同时返回一个空的对象即可.
            System.out.println("登录失败! 用户名或者密码错误! " + user);
//            return R.fail("登录失败! 用户名或者密码错误! " );
            return new User();
        }

        // 2. 如果都匹配, 登录成功! 创建会话!!
        HttpSession session = req.getSession(true);
        session.setAttribute("user", user);
        // 在返回之前, 把 password 给干掉. 避免返回不必要的信息.
        user.setPassword("");
        return user;
    }

    @PostMapping("/register")
    @ResponseBody
    public Object register(String username, String password) {
        User user = null;
        try {
            user = new User();
            user.setUsername(username);
            user.setPassword(password);
            int ret = userMapper.insert(user);
            System.out.println("注册 ret: " + ret);
            user.setPassword("");
        } catch (DuplicateKeyException e) { // spring提供的异常
            // 如果 insert 方法抛出上述异常, 说明名字重复了. 注册失败.
            user = new User();
            System.out.println("注册失败! username = " + username);
        }
        return user;
    }

    @GetMapping("/userInfo")
    @ResponseBody
    public Object getUserInfo(HttpServletRequest req) {
        // 1. 先从请求中获取到会话
        HttpSession session = req.getSession(false);
        if (session == null) {
            // 会话不存在, 用户尚未登录. 此时返回一个空的对象即可.
            System.out.println("[getUserInfo] 当前获取不到 session 对象!");
            return new User();
        }
        // 2. 从会话中获取到之前保存的用户对象.
        User user = (User) session.getAttribute("user");
        if (user == null) {
            System.out.println("[getUserInfo] 当前获取不到 user 对象!");
            return new User();
        }
        user.setPassword("");
        return user;
    }


    // 添加好友
    @PostMapping("/user/addfriend")
    @ResponseBody
    public Object addFriend(@RequestBody Map<String, String> body, HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        Map<String, Object> res = new HashMap<>();

        // 获取当前用户
        User user = (User) session.getAttribute("user");
        if (user == null) {
            res.put("success", false);
            res.put("message", "未登录");
            return res;
        }

        String friendUsername = body.get("username");
        if (friendUsername == null || friendUsername.trim().isEmpty()) {
            res.put("success", false);
            res.put("message", "用户名不能为空");
            return res;
        }

        if (friendUsername.equals(user.getUsername())) {
            res.put("success", false);
            res.put("message", "不能添加自己为好友");
            return res;
        }

        // 查询对方用户
        User friendUser = userMapper.selectByName(friendUsername);
        if (friendUser == null) {
            res.put("success", false);
            res.put("message", "用户不存在");
            return res;
        }

        // 查询是否已有申请或已是好友
        Integer existRequest = friendRequestMapper.checkFriendRequest(user.getUserId(), friendUser.getUserId());
        if (existRequest != null && existRequest > 0) {
            res.put("success", false);
            res.put("message", "已发送过请求或已是好友");
            return res;
        }

        // 插入好友申请（状态为 PENDING）
        int ret = friendRequestMapper.insertFriendRequest(user.getUserId(), friendUser.getUserId());
        if (ret > 0) {
            res.put("success", true);
            res.put("message", "好友申请已发送，等待对方确认");
        } else {
            res.put("success", false);
            res.put("message", "发送失败，请稍后再试");
        }

        return res;
    }


    // 获取好友申请列表
    @GetMapping("/user/friendrequests")
    @ResponseBody
    public Object getFriendRequests(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        Map<String, Object> res = new HashMap<>();

        // 获取当前登录用户
        User currentUser = (User) (session != null ? session.getAttribute("user") : null);
        // 获取当前用户-- 这个功能应该提出来
        if (currentUser == null) {
            res.put("success", false);
            res.put("message", "未登录");
            return res;
        }
        List<FriendRequest> requests = friendRequestMapper.selectFriendRequests(currentUser.getUserId());
        res.put("success", true);
        res.put("data", requests);
        return res;
    }

    // 回复好友申请列表
    @PostMapping("/user/respondfriend")
    @ResponseBody
    public Object respondFriend(@RequestBody Map<String, Object> body, HttpServletRequest request) {
        Map<String, Object> res = new HashMap<>();

        User user = (User) request.getSession().getAttribute("user");

        int requestId = (int) body.get("requestId");
        boolean accept = (boolean) body.get("accept");

        FriendRequest req = friendRequestMapper.getFriendRequestById(requestId);
        if (req == null || req.getToUserId() != user.getUserId()) {
            res.put("success", false);
            res.put("message", "请求无效");
            return res;
        }

        if (accept) {
            friendMapper.addFriend(user.getUserId(), req.getFromUserId());
            friendMapper.addFriend(req.getFromUserId(), user.getUserId());
        }

        friendRequestMapper.deleteFriendRequest(requestId);

        res.put("success", true);
        res.put("message", accept ? "已同意" : "已拒绝");
        res.put("fromUsername", req.getFromUsername());
        res.put("fromUserId", req.getFromUserId());


        return res;
    }

    // 删除好友
    @PostMapping("/user/deletefriend")
    @ResponseBody
    public Object deleteFriend(@RequestBody Map<String, String> body, HttpServletRequest request) {
        Map<String, Object> res = new HashMap<>();
        HttpSession session = request.getSession(false);
        if (session == null) {
            res.put("success", false);
            res.put("message", "未登录");
            return res;
        }

        User user = (User) session.getAttribute("user");
        String friendUsername = body.get("username");

        if (friendUsername == null || friendUsername.isEmpty()) {
            res.put("success", false);
            res.put("message", "用户名不能为空");
            return res;
        }

        User friend = userMapper.selectByName(friendUsername);
        if (friend == null) {
            res.put("success", false);
            res.put("message", "好友不存在");
            return res;
        }

        int deleted = friendMapper.deleteFriend(user.getUserId(), friend.getUserId());
        int deleted2 = friendMapper.deleteFriend(friend.getUserId(), user.getUserId());

        if (deleted > 0 || deleted2 > 0) {
            res.put("success", true);
            res.put("message", "删除成功");
        } else {
            res.put("success", false);
            res.put("message", "你们不是好友");
        }

        return res;
    }




}

